//学科评估
<template>
  <div class="module_">
    <div class="mb8">
      <el-button size="medium" type="primary" @click="handle([],1)">创建模板</el-button>
    </div>
    <el-table :data="tableData" class="flex-1" height="100%" size="medium" border highlight-current-row
      v-loading="tableLoading" stripe @sort-change="tableSortChange" @row-click="rowClick">
      <el-table-column align="center" show-overflow-tooltip prop="template_name" label="模板名" min-width="300" sortable="custom">
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="created_at" label="创建时间" width="180" sortable="custom">
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="status" label="状态" width="150" sortable="custom">
        <template #default="scope">
          {{scope.row.status === 1 ? '已启用':'已停用'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150">
        <div slot-scope="scope" class="tx-r">
          <el-tooltip effect="dark" :content="scope.row.edit?'编辑':'该模板已被使用，不能编辑'" placement="bottom-end">
            <span>
              <el-button :disabled="!scope.row.edit" size="small"  @click.stop="handle(scope.row,2)" icon="el-icon-edit" circle></el-button>
            </span>
          </el-tooltip>
          <el-tooltip effect="dark" :content="scope.row.edit?'删除':'该模板已被使用，不能删除'" placement="bottom-end">
            <el-popconfirm class="ml8" title="确定删除该模板吗？" @confirm="deleteUser(scope.row)">
              <el-button @click.stop="" :disabled="!scope.row.edit" slot="reference" size="small" type="danger" icon="el-icon-delete" circle></el-button>
            </el-popconfirm>
          </el-tooltip>
          <el-tooltip effect="dark" content="使用该模板" placement="bottom-end">
            <el-popconfirm v-if="scope.row.status === 2" class="ml8" title="确定使用该模板吗？" @confirm="useTemplate(scope.row)">
              <el-button @click.stop="" slot="reference" size="small" type="success" icon="el-icon-check" circle></el-button>
            </el-popconfirm>
          </el-tooltip>
        </div>
      </el-table-column>
    </el-table>

    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <el-dialog :visible.sync="editFormVisible" width="700px" @close='dialogClose'
      :close-on-click-modal='false' :close-on-press-escape='false' top="10vh">
      <h2 slot="title" class="tx-c">模板</h2>
      <el-form autocomplete="off" label-width="68px" >
        <el-form-item label="模板名" class="tip">
          <el-input v-model="editForm.template_name" placeholder="请输入模板名"></el-input>
        </el-form-item>
      </el-form>
      <p class="flex-justify-bcenter">
        <el-button type="text" size="mini">总分：100</el-button>
        <span>
          <el-button type="text" size="mini" @click="append({tier:0},'first')">添加一级指标</el-button>
          <el-button type="text" v-if="editForm.template.length > 0" size="mini" @click="rowClick(editForm)">预览</el-button>
        </span>
      </p>
      <el-tree :data="editForm.template" accordion node-key="prop">
        <p class="flex-align-center flex-1 f-16" slot-scope="{ node, data }">
          <span class="flex-1">{{ node.label }}（{{data.score}}分）</span>
          <span>
            <el-button v-if="node.level < 3" type="text" size="mini" @click.stop="() => append(data,'add',node)">
              添加{{conversion(node.level + 1)}}级指标
            </el-button>
            <el-button type="text" size="mini" @click.stop="() => remove(node, data)">
              删除
            </el-button>
            <el-button type="text" size="mini" @click.stop="() => append(data,'edit')">
              编辑
            </el-button>
          </span>
        </p>
      </el-tree>
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading='btnLoading'>确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="editIndicators" :visible.sync="editIndicators" width="700px" @click="editIndicators = false"
      :close-on-click-modal='false' :close-on-press-escape='false' top="10vh">
      <el-form autocomplete="off" label-width="85px">
        <el-form-item label="指标名称" class="tip">
          <el-input type="text" v-model="indicatorsForm.label" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="指标分数" class="tip">
          <el-input type="number" v-model.number="indicatorsForm.score" placeholder="请输入分数" @input="checkScore">
            <template slot="append">分</template>
          </el-input>
        </el-form-item>
        <el-form-item label="评估科室" v-if="indicatorsForm.tier == 1" class="tip">
          <!-- @change="(id)=>{indicatorsForm.department_id = id}" -->
          <el-select size="medium" value-key="id" v-model="choseKeshi" clearable filterable placeholder="请输入科室名称搜索" @change="choseChage">
            <el-option
              v-for="item in cacheDepartments"
              :key="'departments_' + item.id"
              :label="item.name"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <template v-else-if="indicatorsForm.tier >= 3">
          <el-form-item label="指标说明">
            <wangeditor ref="wangeditor" @getContent="getContent" :editorContent='indicatorsForm.instructions' />
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" autosize v-model="indicatorsForm.desc" placeholder="请输入备注">
            </el-input>
          </el-form-item>
        </template>
        
      </el-form>
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editIndicators = false">取 消</el-button>
        <el-button type="primary" @click="indicatorsInfo">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="previewObj.preview" :visible.sync="previewObj.preview" width="80%" @click="previewObj.preview = false"
      :close-on-click-modal='false' :close-on-press-escape='false' top="10vh">
      <h2 slot="title" class="tx-c">{{previewObj.title}}</h2>
      <table class="table_cell" border="1" cellspacing="0" v-loading="previewObj.loading">
        <tr>
          <th>一级指标</th>
          <th>二级指标</th>
          <th>三级指标</th>
          <th>三级指标说明</th>
          <th>备注</th>
        </tr>
        <tr v-for="(item,i) in previewObj.previewList" :key="i">
          <td  v-for="(v,i) in item" :key="'label' + i" :rowspan="v.rowspan" v-html="v.label"></td>
        </tr>
      </table>
    </el-dialog>
  </div>
</template>

<script>
  import {
    Apievaluatetemplate,
    ApievaluatetemplateAdd,
    ApievaluatetemplatePut,
    Apiusetemplate,
    ApievaluatetemplateDel,
  } from '@/api'
  import {
    debounce,
    utils_conversion
  } from "@/utils/index";
  import wangeditor from "@/components/wangeditor"
  import {mapState} from "vuex"
  export default {
    name: 'subject_evaluationModule',
    components:{
      wangeditor
    },
    computed:{
      ...mapState(['cacheDepartments'])
    },
    data() {
      return {
        tableData: [],
        editFormVisible: false,
        editIndicators: false,
        indicatorsForm:{
          label:'',
          score: null,
          tier: null,
          instructions: '',
          desc: '',
          department_id: '',
        },
        editForm: {
          template_name: '',
          template: []
        }, //修改或者查看详情

        pageparm: {
          page: 1,
          perPage: 20,
          total: null,
          sort_str: null,
          sort_order: 'desc',
        },
        tableLoading: false,

        btnLoading: false,

        theStaging:{
          way:'',
          data:null,
          node:null
        },

        previewObj:{preview:false,previewList:[],loading:false,title:''},

        choseKeshi:{}
      }
    },
    mounted() {
      this.getList()
    },
    methods: {
      rowClick(row){
        this.previewObj.preview = true
        this.previewObj.loading = true
        this.previewObj.title = row.template_name
        const template = row.template
        const tableArr = this.parseTreeToRow(template)
        for(let i = tableArr.length - 1; i >= 0; i--){
          if(i >= 1){
            const item = tableArr[i]
            const temp = tableArr[i - 1]
            if(item[1] && (item[1].label == temp[1].label)){
              item.splice(1, 1)
            }
            if(item[0].label == temp[0].label){
              item.splice(0, 1)
            }
          }
          if(tableArr[i].length < 3){
            tableArr[i].push(...Array.from({length: 5-tableArr[i].length}, () => ({})))
          }
        }
        this.previewObj.previewList = tableArr
        this.previewObj.loading = false
      },
      //转成可渲染的table数据
      parseTreeToRow(node, data = [], row = []) {
        if (node.length === 0) {
          data.push(row);
        } else {
          for (let i = 0; i < node.length; i++) {
            const childObj = node[i];
            const cell = {
              label: `${childObj.label}(${childObj.score}分)</br>${childObj.tier === 1 ? '('+childObj.department_name+')' : ''}`,
            };
            let newRow
            if (childObj.tier === 3) {
              cell.rowspan = 1
              newRow = [...row, cell, {label: childObj.instructions}, {label: childObj.desc}]
            } else {
              cell.rowspan = this.computeLeafCount(childObj)
              newRow = [...row, cell]
            }
            this.parseTreeToRow(childObj.children, data, newRow);
          }
        }
        return data;
      },
      //添加rowspan
      computeLeafCount(node) {
        if (node.children.length === 0) {
          return 1;
        } else {
          let leafCount = 0;
          for (let i = 0; i < node.children.length; i++) {
              leafCount = leafCount + this.computeLeafCount(node.children[i]);
          }
          return leafCount;
        }
      },
      checkScore(v){
        if(v.includes('.')){
          let [a,b] = v.split('.')
          if(b.length > 1) b = b.slice(0,1)
          this.indicatorsForm.score = a + "." + b
        }
      },
      deleteUser(item){
        ApievaluatetemplateDel(item.id).then(res=>{
          this.$message.success('删除成功');
          this.getList()
        }).catch(()=>{
          this.$message.error('删除失败');
        })
      },
      useTemplate(item){
        Apiusetemplate(item.id).then(res => {
          this.$message.success('已成功使用' + item.template_name);
          this.getList()
        }).catch(()=>{
          this.$message.error('使用失败');
        })
      },
      handle(row,i){
        if(i === 1){
          this.editForm = {
            // template: JSON.parse(JSON.stringify(template)),
            template: [],
            template_name: ''
          }
        }else{
          this.editForm.id = row.id
          this.editForm.template = JSON.parse(JSON.stringify(row.template))
          this.editForm.template_name = row.template_name
        }
        this.editFormVisible = true
      },
      getContent(html){
        this.indicatorsForm.instructions = html
      },
      conversion(key){
        return utils_conversion(key)
      },
      append(data,way,node){
        this.theStaging.way = way
        this.theStaging.data = data
        if(way === 'edit'){
          this.indicatorsForm = {...data}
          if(data.tier === 1) this.choseKeshi = {id:data.department_id}
        }else{
          this.indicatorsForm = {
            label: '',
            score: null,
            tier: data.tier + 1,
            instructions: '',
            desc: '',
            // department_id: null,
          }
          this.theStaging.node = node
        }
        this.editIndicators = true
      },
      remove(node, data){
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.prop === data.prop);
        children.splice(index, 1);
      },
      indicatorsInfo: debounce(function(){
        const indicatorsForm = this.indicatorsForm
        if(!indicatorsForm.label){
          this.$message.error('请输入指标名称');
          return
        }
        if(!indicatorsForm.score){
          this.$message.error('请输入指标分数');
          return
        }
        if(indicatorsForm.tier == 1 && !indicatorsForm.department_id){
          this.$message.error('请选择评估科室');
          return
        }
        if(this.theStaging.way === 'add'){
          const newChild = {...indicatorsForm,prop:'a' + Date.now(),children: []}
          this.theStaging.data.children.push(newChild)
          this.theStaging.node.expanded = true
        }else if(this.theStaging.way === 'edit'){
          this.theStaging.data.label = indicatorsForm.label
          this.theStaging.data.score = indicatorsForm.score
          this.theStaging.data.instructions = indicatorsForm.instructions
          this.theStaging.data.desc = indicatorsForm.desc
          if(indicatorsForm.tier == 1) {
            this.theStaging.data.department_id = indicatorsForm.department_id
            this.theStaging.data.department_name = indicatorsForm.department_name
          }
        }else if(this.theStaging.way === 'first'){
          const newChild = {...indicatorsForm,prop:'a' + Date.now(),children: []}
          this.editForm.template.push(newChild)
        }
        this.editIndicators = false
      },800,true),
      choseChage(item){
        this.indicatorsForm.department_id = item.id
        this.indicatorsForm.department_name = item.name
      },
      tableSortChange(column) {
        if (column.order === "descending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "desc";
        } else if (column.order === "ascending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "asc";
        } else {
          this.pageparm.sort_str = null;
          this.pageparm.sort_order = null;
        }
        this.getList()
      },
      //搜索
      clearSearch() {
        // this.$refs.search_d.clear()
      },
      searchChane(i, val) {
        this.pageparm[val] = i
        this.pageparm.page = 1
        this.getList()
      },
      //分页
      callFather(pageparm) {
        this.pageparm.page = pageparm.page
        this.pageparm.perPage = pageparm.perPage
        this.getList()
      },
      getList() {
        this.tableLoading = true
        Apievaluatetemplate(this.pageparm).then(({data, page}) => {
          this.tableData = data || []
          this.pageparm.total = page.total
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      dialogClose() {
      },
      submit: debounce(function () { //提交  修改或新增
        const options = this.editForm
        if(!options.template_name){
          this.$message.error('请输入模板名');
          return
        }

        this.btnLoading = true

        const objTip = {}
        const isThreeTier = (arr) => {
          for(let j = 0 ;j < arr.length;j ++){
            if(arr[j].children.length > 0){
              isThreeTier(arr[j].children)
            }else{
              if(arr[j].tier < 3){
                objTip.tier = arr[j].tier
                objTip.label = arr[j].label
                return
              }
            }
          }
        }
        isThreeTier(options.template)
        if(objTip.label){
          this.$message.error(objTip.label + '缺少'+ (objTip.tier + 1) + '级指标');
          this.btnLoading = false
          return
        }

        //
        let scoreTitle = 100
        let flag = true
        let tipTitle = "一级指标分数和与总分不相等"
        function checkSubmit (arr) {
          const sumTitle = arr.reduce((sum,item)=>{
            return sum + Number(item.score)  
          },0)
          if(sumTitle !== scoreTitle){
            flag = false
            return
          }
          for(let i = 0;i < arr.length;i ++){
            if(arr[i].children.length > 0){
              if(!flag) break
              scoreTitle = Number(arr[i].score)
              tipTitle = arr[i].label + '子项分数分配异常'
              checkSubmit(arr[i].children)
            }
          }
        }
        checkSubmit(options.template)
        if(!flag){
          this.$message.error(tipTitle);
          this.btnLoading = false
          return
        }
        
        if(options.id){
          ApievaluatetemplatePut(options.id,options).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            this.editFormVisible = false
            this.getList()
          }).catch(()=>{
            this.$message({
              type: 'error',
              message: '修改失败!'
            });
          }).finally(() => {
            this.btnLoading = false
          });
        }else{
          ApievaluatetemplateAdd(options).then(res => {
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
            this.editFormVisible = false
            this.getList()
          }).catch(()=>{
            this.$message({
              type: 'error',
              message: '添加失败!'
            });
          }).finally(() => {
            this.btnLoading = false
          });
        }
      }, 800, true)
    },

  }
</script>
<style lang='less' scoped>
/deep/ .el-tree-node__content{
  padding-top:4px ;
  padding-bottom: 4px;
}
.table_cell {
    width: 100%;
    font-size: 16px;
    border-color: #EBEEF5;
    th {
      padding: 8px;
      font-size: 18px;
      white-space: nowrap;
    }
    td {
      padding:4px 8px;
    }
  }
</style>